package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Charts;
import com.example.springboot.service.ChartsService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * 统计图前端操作接口
 **/
@RestController
@RequestMapping("/chartssss")
public class ChartsController {

    @Resource
    ChartsService chartsService;

    /**
     * 新增
     */
    @PostMapping("/add")
    public Result add(@RequestBody Charts charts) {
        try {
            chartsService.add(charts);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据错误");
            } else {
                return Result.error("系统错误");
            }
        }
        return Result.success();
    }


    /**
     * 根据ID查询
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Charts charts = chartsService.getById(id);
        return Result.success(charts);
    }

    /**
     * 根据Name值查询
     */
    @GetMapping("/selectByName/{name}")
    public Result selectByName(@PathVariable String name) {
        Charts charts = chartsService.getByName(name);
        return Result.success(charts);
    }

    /**
     * 查询所有
     */
    @GetMapping("/selectAll")
    public Result selectAll(Charts charts) {
        List<Charts> chartsList = chartsService.SelectAll();
        return Result.success(chartsList);
    }

    /**
     * 分页查询
     */
    @GetMapping("/selectByPage")
    public Result selectPage(@RequestParam String name,
                             @RequestParam Integer pageNum,
                             @RequestParam Integer pageSize) {
        QueryWrapper<Charts> queryWrapper = new QueryWrapper<Charts>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        Page<Charts> page = chartsService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

}